import { useState } from 'react'
import { connect } from 'react-redux'
import { Form, Input, Button, Layout } from 'antd';
import { useRouteMatch } from 'react-router-dom'

function UserInfo({ users, dispatch }, props) {
  const {
    params: { id },
  } = useRouteMatch();

  const [newName, setNewName] = useState('');
  const [newSex, setNewSex] = useState('');
  const [newAddress, setNewAddress] = useState('');
  const [newTags, setNewTags] = useState('');

  let actualUser = users.find(user => user.id === id);

  if(!actualUser){
    actualUser = {id:"",name:"",sex:"",address:"",tags:""};
  }

  console.log(actualUser);

  function updateUserHandler() {
    if(actualUser.id == ""){
        alert("这是添加页面，请从列表修改进入此页面！");
        return false;
    }else{
        dispatch({
            type: 'update_user',
            payload: {
              user: {
                  //   ...actualUser,//全部拷贝
                  id:actualUser.id,
                  name: newName == "" ? actualUser.name : newName,
                  sex:newSex == "" ? actualUser.sex : newSex,
                  address:newAddress == "" ? actualUser.address : newAddress,
                  tags:newTags == "" ? actualUser.tags : newTags
              },
            },
        })
    }
  }

  function addUserHandler() {
    if(actualUser.id != ""){
        alert("这是修改页面，请直接点击‘employee’进入添加页面！");
        return false;
    }else{
        dispatch({
            type: 'create_user',
            payload: {
              user: {
                  //   ...actualUser,//全部拷贝
                  name: newName,
                  sex:newSex,
                  address:newAddress,
                  tags:newTags
              },
            },
        })
        alert("添加成功，请到列表页进行查看！");
    }
  }

  return (
      <div style={{textAlign:"center"}}>
          &nbsp;
          <Form>
            姓名(原：{actualUser.name})：<Input style={{width:"500px"}} onChange={e => setNewName(e.target.value)}/><br/><br/>
            性别（原：{actualUser.sex}）：<Input style={{width:"500px"}} onChange={e => setNewSex(e.target.value)}/><br/><br/>
            地址（原：{actualUser.address}）：<Input style={{width:"500px"}} onChange={e => setNewAddress(e.target.value)}/><br/><br/>
            兴趣(原：{actualUser.tags})：<Input style={{width:"500px"}}  onChange={e => setNewTags(e.target.value)}/><br/><br/>
          </Form>
          <Button type="primary" onClick={() => updateUserHandler(actualUser.id)}>修改</Button>&nbsp;&nbsp;&nbsp;&nbsp;
          <Button type="primary" onClick={() => addUserHandler(actualUser.id)}>新增</Button>
      </div>
  )
}

export default connect(({ users }) => ({ users }))(UserInfo)
